package com.vf.admin.utils.Base64Image;

import com.vf.admin.utils.StringEx;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class GenerateImage {


    /**
     * 创建目录
     * @param destDirName 目标目录名
     * @return 目录创建成功返回true，否则返回false
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
//			System.out.println(destDirName +" 目标目录已存在！");
            return true;
        }
        if (!destDirName.endsWith(File.separator))
            destDirName = destDirName + File.separator;
        if (dir.mkdirs()) {   // 创建单个目录
//			System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
//			System.out.println("创建目录" + destDirName + "失败！");
            return false;
        }
    }

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        File srcFile=new File(sPath);
        File[] files = srcFile.listFiles();
        for(File f:files){
            if(f.isDirectory()){
                System.out.println("QQQQQQ");
                //deleteFolder(f);//递归调用
            }else{
                System.out.println(f.getName()+"---"+f.delete());//删除文件
            }
        }
        return true;
    }





    //图片转为base64
    public static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String resultStr = encoder.encode(data).trim().replaceAll("\n", "").replaceAll("\r", "");
//        String resultStr = encoder.encode(Objects.requireNonNull(data));
        // 返回Base64编码过的字节数组字符串
        System.out.println("本地图片转换Base64:" + resultStr);
        return resultStr;
    }

    //base64转为图片
    public static boolean getBaseImage(String imgStr, String path) {
        if (StringEx.isNull(imgStr)){// 图像数据为空
            return false;
        }

        if(imgStr.contains("base64,")){
            imgStr = imgStr.substring(imgStr.indexOf("base64,")+7,imgStr.length());
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();

            return true;
        } catch (Exception e) {
            return false;
        }

    }

    // 将网络图片转成Base64码， 此方法可以解决解码后图片显示不完整的问题
    public static String imgBase64(String imgURL) {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(imgURL);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "fail";//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outPut.toByteArray());
    }



}
